# encoding: utf-8


def table99(file='table99.txt', encoding='utf8'):
    """
    :param file: filename to save data in
    :param encoding: code type for file
    :return:
    >>> table99('table99.txt')
    >>> with open('table99.txt', mode='rt', encoding='utf8') as fp: fp.readline()
    '1x1 =  1  \\n'
    >>> import linecache
    >>> linecache.getline('table99.txt', 9)
    '9x1 =  9  9x2 = 18  9x3 = 27  9x4 = 36  9x5 = 45  9x6 = 54  9x7 = 63  9x8 = 72  9x9 = 81  \\n'
    """
    with open(file, 'w', encoding=encoding) as f:
        for i in range(1, 10):
            line = ''
            for j in range(1, 10):
                if i >= j:
                    line += '{}x{} = {:2d}  '.format(i, j, i*j)
            f.write(line+'\n')


def demo_open_write():
    """
    创建demo.txt: 以文本方式打开文件，权限为读写，编码为utf8
    demo.txt:
    line-1
    line-2

    line-3
    """
    lines = ['line-1\n', 'line-2\n', '\n', 'line-3\n']
    with open(file='demo.txt', mode='wt', encoding='utf8') as fp:
        fp.writelines(lines)


def demo_open_read(op='read'):
    """
    测试有关文件的读操作：read, readline, readlines
    >>> demo_open_read('read')
    line-1
    >>> demo_open_read('readline')
    line-1
    line-3
    <BLANKLINE>
    <BLANKLINE>
    >>> demo_open_read('readlines')
    ['line-1\\n', 'line-2\\n', '\\n', 'line-3\\n']
    line-1
    line-2
    <BLANKLINE>
    line-3
    """
    demo_open_write()

    if op == 'read':
        with open(file='demo.txt', mode='r', encoding='utf8') as fp:
            read_var = fp.read(7)		                     # 从文件中读出6个字符数据：line-1\n，存放到变量read_var
            print(read_var, end='')                          # 去除'\n'后打印

    if op == 'readline':
        with open(file='demo.txt', mode='r', encoding='utf8') as fp:
            print(fp.readline(), end='') 		             # 读出：'line-1\n'，去除'\n'后打印
            fp.readline()                                    # 读出第2-3行，不打印
            fp.readline()                                    #
            print(fp.readline(), end='')                     # 读出：'line-3\n', 去除'\n'后打印
            print(fp.readline())                             # 到达文件尾时，返回空字符串
            print(fp.readline())                             # 到达文件尾时，返回空字符串

    if op == 'readlines':
        with open(file='demo.txt', mode='r', encoding='utf8') as fp:
            print(fp.readlines())
        with open(file='demo.txt', mode='r', encoding='utf8') as fp:
            for line in fp.readlines():
                print(line, end='') 		             # 读出所有行，去除'\n'后打印


def demo_open_append():
    """
    write(write_var) 将write_var写入文件，返回写入字符数
    在demo.txt文件中，先添加一行字符a-z，再添加三行：a1,b2,c3
    显示写入的字符a-z，字符数27
    最后读出显示所有行的列表
    >>> demo_open_append()
    write string：abcdefghijklmnopqrstuvwxyz
    write char number=27
    ['line-1\\n', 'line-2\\n', '\\n', 'line-3\\n', 'abcdefghijklmnopqrstuvwxyz\\n', 'a1\\n', 'b2\\n', 'c3\\n']
    """
    demo_open_write()
    with open(file='demo.txt', mode='a+', encoding='utf8') as fp:
        s = ''.join([chr(x) for x in range(97, 97+26)]) + '\n'      # 'abc...z'
        write_num = fp.write(s)
        print('write string：{}write char number={}'.format(s, write_num))
        fp.writelines(['a1\n', 'b2\n', 'c3\n'])	                    # 写入3行字符串，每行尾部需要增加'\n'
        fp.seek(0)
        print(fp.readlines())


def demo_open_read_line_by_rowno(file, rowno):
    rs = ''
    with open(file) as fp:
        rowlen = len(fp.readline())
        fp.seek((rowno-1)*rowlen, 0)
        rs = fp.readline()
    return rs
